<?php
/**
 * Created by PhpStorm.
 * User: paulLu
 * Date: 2016/2/22
 * Time: 13:57
 */
namespace App\Http\Controllers\Job;
use App\Http\Controllers\ApiController;
use App\Http\Components\UserComponent;
use App\Http\Controllers\Myorder\EvaluateController;
use App\library\juhe\Identify;
use App\library\UtilFunction;
use App\Models\CollectionModel;
use App\Models\ConfigModel;
use App\Models\JobClassModel;
use App\Models\JobModel;
use App\Models\JobOrderModel;
use App\Models\UserModel;
use App\Models\UserProfileModel;
use App\Models\UserSettingModel;
use App\Models\UserAccountModel;
use Illuminate\Http\Request;

use App\Http\Components\OuterDataComponent;
use App\library\UtilRegular;

/**
 * 提交订单
 */
class SubOrderController extends ApiController{

    public function __construct(){
        parent::__construct();
    }

    /**
     * 版本控制，对应app版本跳转对应接口
     * @param Request $request
     * @author paulLu
     */
    /*版本控制，对应app版本跳转对应接口*/
    public function version_invoke($function,Request $request){
        $appversion = $request->input('appversion');
        $apptype = $request->input('apptype');
        if ($appversion && $apptype) {
            try{
                return call_user_func_array(array($this,$function), array($request));
            }catch(\Exception $e){
                return $this->json('0','系统错误'.$e->getMessage());
            }
        }else{
            return $this->json('102','该app版本下无此接口，请更新app');
        }
    }


    /**
     * 需求
     * 应邀
     */
    public function demand(Request $request){
        $user = UserComponent::check_token($request);

        $user_id = $user['user_id'];
        $job_id = $request->input('job_id');
        $remark = $request->input('remark');

        if(empty($job_id)){
            return $this->json('0','参数为空!');
        }
        $job = JobModel::where('model',2)->where("id",$job_id)->first();
        if(!$job){
            return $this->json('0','该需求不存在!');
        }
        $job = $job->toArray();

        if($user_id == $job["user_id"]){
            return $this->json('0','自己不能给自己下单!');
        }
        if($user["status"] == 2 && time()<$user["transaction_fobit_time"]){
            return $this->json('0','您已被禁止交易!');
        }
        $user2 = UserModel::where("user_id",$job["user_id"])->first()->toArray();
        if($user2["status"] == 2 && time()<$user2["transaction_fobit_time"]){
            return $this->json('0','对方已被禁止交易!');
        }


        //验证该用户账户余额
        $userAccount = UserAccountModel::where("user_id",$job["user_id"])->first();
        $userAccountArr = $userAccount->toArray();
        UserComponent::checkBalance($userAccountArr,($job["order_price"]*100));

        //获取保安员
        $salety = $this->_getFiveSafety($job["lon"],$job["lat"]);



        $jobOrder = new JobOrderModel();
        $jobOrder->user_id = $user_id;
        $jobOrder->order_sn = date("YmdHis").rand(1000,9999);
        $jobOrder->job_user_id = $job["user_id"];
        $jobOrder->job_id = $job_id;
        $jobOrder->job_class_id = $job["job_class_id"];
        $jobOrder->job_class_name = $job["job_class_name"];
        $jobOrder->job_model = $job["model"];
        $jobOrder->start_time = $job["start_time"];
        $jobOrder->unit_price = $job["price"];
        $jobOrder->service_time = $job["service_hourse"];
        $jobOrder->address = $job["service_address"];
        $jobOrder->price = $job["order_price"];
        $jobOrder->lon = $job["lon"];
        $jobOrder->lat = $job["lat"];
        $jobOrder->voice = $job["voice"];
        $jobOrder->voice_time = $job["voice_time"];
        $jobOrder->introduce = $job["introduce"];
        $jobOrder->trip_mode = $job["trip_mode"];
        $jobOrder->age = $job["age"];
        $jobOrder->gender = $job["gender"];
        $jobOrder->job_remark = $job["remark"];
        $jobOrder->remark = $remark;
        $jobOrder->create_time = time();
        if(!empty($salety)){
            $jobOrder->safety_user_id = $salety["user_id"];
        }
        $agent = $this->_getAgent($job["lon"],$job["lat"]);
        $jobOrder->service_province = $agent["service_province"];
        $jobOrder->service_city = $agent["service_city"];
        $jobOrder->service_district = $agent["service_district"];
        if(!empty($agent["profile"])){
            $jobOrder->agent_user_id = $agent["user_id"];
        }
        $result = $jobOrder->saveOrFail();
        if($result){
            UserAccountModel::where("user_id",$user_id)->increment("send_order_num",1);
            UserAccountModel::where("user_id",$job["user_id"])->increment("receive_order_num",1);
            //冻结下单金额
            $userAccount->frozen = $userAccount->frozen+($job["order_price"]*100);
            $userAccount->saveOrFail();
            //订单通知
            $send_data = array(
                'user_id'=>$job["user_id"],
                'message'=>"新订单",
                "desc"=>"您有新的订单啦",
            );
            UtilFunction::sendPush($send_data);
            return $this->json('1','下单成功');
        }else{
            return $this->json('0','下单失败，请稍后重试!');
        }
    }

    /**
     * 兼职
     * 下单约她
     */
    public function work(Request $request){
        $user = UserComponent::check_token($request);

        $user_id = $user['user_id'];
        $job_id = $request->input('job_id');
        $sub_service_address = $request->input('service_address');  //服务地址
        $sub_start_time = $request->input('start_time');  //开始时间
        $sub_service_time = $request->input('service_time');    //服务时间

        $trip_mode = $request->input('trip_mode');
        $lon = $request->input('lon');  //经度
        $lat = $request->input('lat');  //纬度
        $remark = $request->input('remark');
        if(empty($job_id)){
            return $this->json('0','参数为空!');
        }
        $job = JobModel::where('model',1)->where("id",$job_id)->first();
        if(!$job){
            return $this->json('0','该兼职不存在!');
        }
        $job = $job->toArray();

        if($user_id == $job["user_id"]){
            return $this->json('0','自己不能给自己下单!');
        }
        if($user["status"] == 2 && time()<$user["transaction_fobit_time"]){
            return $this->json('0','您已被禁止交易!');
        }
        $user2 = UserModel::where("user_id",$job["user_id"])->first()->toArray();
        if($user2["status"] == 2 && time()<$user2["transaction_fobit_time"]){
            return $this->json('0','对方已被禁止交易!');
        }


        if($sub_service_time<$job["service_hourse"]){
            return $this->json('0','服务时间必须大于'.$job["service_hourse"]."小时");
        }
        if($job["job_class_id"] == 7){
            if(empty($trip_mode)){
                return $this->json('0','请选择出行方式！');
            }
        }

        //验证该用户账户余额
        $userAccount = UserAccountModel::where("user_id",$user_id)->first();
        $userAccountArr = $userAccount->toArray();
        UserComponent::checkBalance($userAccountArr,($job["price"]*100));
        //获取保安员
        $salety = $this->_getFiveSafety($lon,$lat);

        $jobOrder = new JobOrderModel();
        $jobOrder->user_id = $user_id;
        $jobOrder->order_sn = date("YmdHis").rand(1000,9999);
        $jobOrder->job_user_id = $job["user_id"];
        $jobOrder->job_id = $job_id;
        $jobOrder->job_class_id = $job["job_class_id"];
        $jobOrder->job_class_name = $job["job_class_name"];
        $jobOrder->job_model = $job["model"];
        $jobOrder->start_time = $sub_start_time;
        $jobOrder->unit_price = $job["price"];
        $jobOrder->service_time = $sub_service_time;
        $jobOrder->introduce = $job["introduce"];
        $jobOrder->address = $sub_service_address;
        $jobOrder->price = round($sub_service_time*$job["price"],2);
        $jobOrder->voice = $job["voice"];
        $jobOrder->voice_time = $job["voice_time"];
        $jobOrder->trip_mode = $trip_mode;
        $jobOrder->age = $job["age"];
        $jobOrder->lon = $lon;
        $jobOrder->lat = $lat;
        $jobOrder->gender = $job["gender"];
        $jobOrder->job_remark = $job["remark"];
        $jobOrder->remark = $remark;
        $jobOrder->create_time = time();
        if(!empty($salety)){
            $jobOrder->safety_user_id = $salety["user_id"];
        }
        $agent = $this->_getAgent($lon,$lat);
        $jobOrder->service_province = $agent["service_province"];
        $jobOrder->service_city = $agent["service_city"];
        $jobOrder->service_district = $agent["service_district"];
        if(!empty($agent["profile"])){
            $jobOrder->agent_user_id = $agent["user_id"];
        }

        $result = $jobOrder->saveOrFail();
        if($result){
            UserAccountModel::where("user_id",$user_id)->increment("send_order_num",1);
            UserAccountModel::where("user_id",$job["user_id"])->increment("receive_order_num",1);
            //冻结下单金额
            $userAccount->frozen = $userAccount->frozen+($job["price"]*100);
            $userAccount->saveOrFail();
            //订单通知
            $send_data = array(
                'user_id'=>$job["user_id"],
                'message'=>"新订单",
                "desc"=>"您有新的订单啦",
            );
            UtilFunction::sendPush($send_data);
            return $this->json('1','下单成功');
        }else{
            return $this->json('0','下单失败，请稍后重试!');
        }
    }

    /**
     * 获取5公里之类最近的安保员
     */
    public function _getFiveSafety($lon,$lat){
        $safe_list = UserProfileModel::where("is_safety",2)->get()->toArray();
        $min_distance = 0;
        $result = array();
        foreach($safe_list AS $sitem){
            $distance = UtilFunction::get_distance_true($lat,$lon,$sitem["safety_lat"],$sitem["safety_lng"]);
            if(($min_distance==0 || $distance<$min_distance) && $distance <= 5000){//获取5公里以内距离最短的保安员
                $min_distance = $distance;
                $result = $sitem;
            }
        }
        return $result;
    }

    /**
     * 通过经纬度 获取代理商
     */
    public function _getAgent($lon,$lat){
        $result = array();
        $service_address_arr  = UtilFunction::getAddressByLatLon($lat,$lon);
        $service_province = $service_address_arr["province"];
        $service_city = $service_address_arr["city"];
        $service_district = $service_address_arr["district"];
        $result["service_province"] = $service_province;
        $result["service_city"] = $service_city;
        $result["service_district"] = $service_district;
        $agentProfile = UserProfileModel::where("is_agent",1)->where("agent_province_name",$service_province)->where("agent_city_name",$service_city)->where("agent_district_name",$service_district)->first();
        if($agentProfile){
            $profile =  $agentProfile->toArray();
            $result["profile"] = $profile;
        }else{
            $result["profile"] = "";
        }
        return $result;
    }



}